package com.bank.gui;

import com.bank.utils.CommunicationWrapper;
import com.bank.utils.Operation;
import com.bank.utils.TextFieldLimiter;
import com.bank.utils.Toast;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.text.AbstractDocument;
import org.json.JSONException;
import org.json.JSONObject;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Moofie
 */
public class DepositPanel extends javax.swing.JPanel {

    private CommunicationWrapper cw;
    private String branchCode;
    private int portNo;
    /**
     * Creates new form DepositPanel
     */
    private boolean validate;

    public DepositPanel(CommunicationWrapper cw, String branchCode, int portNo) {
        this.cw = cw;
        this.branchCode = branchCode;
        this.portNo = portNo;
        initComponents();
    }

    /**
     * reset text fields
     */
    private void reset() {
        txtAccNumber.setText("");
        txtICNumber.setText("");
        txtAmountDeposit.setText("");
    }

    /**
     * check if the given string is numeric or not
     *
     * @param str string to be checked
     * @return result of checking
     */
    public static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtAccNumber = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtICNumber = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtAmountDeposit = new javax.swing.JTextField();
        btnReset = new javax.swing.JButton();
        btnSubmit = new javax.swing.JButton();
        jlblAccBalance = new javax.swing.JLabel();
        jlblBalance = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Account Number ");
        add(jLabel1);
        jLabel1.setBounds(20, 40, 220, 30);

        AbstractDocument aDoc = (AbstractDocument)txtAccNumber.getDocument();
        aDoc.setDocumentFilter(new TextFieldLimiter("\\d{0,14}"));
        txtAccNumber.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        add(txtAccNumber);
        txtAccNumber.setBounds(20, 70, 400, 30);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("IC Number");
        add(jLabel2);
        jLabel2.setBounds(20, 110, 220, 30);

        AbstractDocument aDocIC = (AbstractDocument)txtICNumber.getDocument();
        aDocIC.setDocumentFilter(new TextFieldLimiter("\\d{0,12}"));
        txtICNumber.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        add(txtICNumber);
        txtICNumber.setBounds(20, 140, 400, 30);

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Amount to Deposit");
        add(jLabel3);
        jLabel3.setBounds(20, 180, 180, 30);

        AbstractDocument aDocAmount = (AbstractDocument)txtAmountDeposit.getDocument();
        aDocAmount.setDocumentFilter(new TextFieldLimiter("\\d{0,5}"));
        txtAmountDeposit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtAmountDeposit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtAmountDepositActionPerformed(evt);
            }
        });
        add(txtAmountDeposit);
        txtAmountDeposit.setBounds(20, 210, 400, 30);

        btnReset.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });
        add(btnReset);
        btnReset.setBounds(20, 320, 160, 50);

        btnSubmit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnSubmit.setText("Submit");
        btnSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSubmitActionPerformed(evt);
            }
        });
        add(btnSubmit);
        btnSubmit.setBounds(260, 320, 160, 50);

        jlblAccBalance.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblAccBalance.setText("Account Balance                        : ");
        add(jlblAccBalance);
        jlblAccBalance.setBounds(20, 250, 210, 30);

        jlblBalance.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jlblBalance.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        add(jlblBalance);
        jlblBalance.setBounds(240, 250, 170, 30);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("CASH DEPOSIT");
        add(jLabel5);
        jLabel5.setBounds(20, 5, 400, 20);
        add(jSeparator1);
        jSeparator1.setBounds(10, 25, 420, 5);
    }// </editor-fold>//GEN-END:initComponents

    private void txtAmountDepositActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAmountDepositActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtAmountDepositActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        reset();
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSubmitActionPerformed
        // prepare a string for errors
        StringBuilder check = new StringBuilder("<html>Errors");
        validate = true;
        if (txtAccNumber.getText().length() == 0) {
            validate = false;
            check.append("<br />Please enter account number");
        }
        if (txtICNumber.getText().length() == 0) {
            validate = false;
            check.append("<br />Please enter ic number");
        }
        if (txtAmountDeposit.getText().length() == 0) {
            validate = false;
            check.append("<br />Please enter deposit amount");
        }
        if (!validate) {
            // validation not true, display error message
            check.append("</html>");
            Toast.makeText(getParent(), 150, "" + check, Toast.LENGTH_LONG).display();
        } else {
            // validation true, proceed to constructing data to be send to server
            try {
                JSONObject j = new JSONObject();
                // specific operation
                j.put("operation", Operation.DEPOSIT);
                JSONObject content = new JSONObject();
                // put in all necessary data
                content.put("accNo", txtAccNumber.getText());
                content.put("icNo", txtICNumber.getText());
                content.put("amount", Double.parseDouble(txtAmountDeposit.getText()));
                content.put("port", this.portNo);
                content.put("bCode", this.branchCode);
                content.put("address", InetAddress.getLocalHost().getHostAddress());
                j.put("content", content);
                // send constructed data to server
                cw.send(j, InetAddress.getLocalHost(), 5000);
                // wait for reply from server
                JSONObject js = cw.receive();
                JSONObject result = js.getJSONObject("content");
                if (result.get("result").toString().equalsIgnoreCase("Success")) {
                    // operation success, display returned value
                    Toast.makeText(getParent(), "Success", Toast.LENGTH_SHORT).display();
                    jlblBalance.setText("RM " + String.format("%.2f", result.getDouble("balance")));
                } else {
                    // operation failed, display error message
                    Toast.makeText(getParent(), "Deposit unsuccessful.", Toast.LENGTH_SHORT).display();
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            } catch (UnknownHostException ex) {
                ex.printStackTrace();
            }

        }
    }//GEN-LAST:event_btnSubmitActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSubmit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel jlblAccBalance;
    private javax.swing.JLabel jlblBalance;
    private javax.swing.JTextField txtAccNumber;
    private javax.swing.JTextField txtAmountDeposit;
    private javax.swing.JTextField txtICNumber;
    // End of variables declaration//GEN-END:variables
}
